<template>
  <basic-layout
    :title="title"
    show-back
    class="chat-detail"
  >
    <chat-window
      ref="chatWindowRef"
      :other-avatar="otherAvatar"
      :placeholder="placeholder"
      :is-A-I="isAI"
      @send="handleSend"
    />
  </basic-layout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import ChatWindow from '@/components/chat/ChatWindow.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const chatWindowRef = ref()

const isAI = route.query.type === 'ai'
const title = ref(isAI ? 'DeepSeek AI' : route.query.name || '聊天')
const otherAvatar = isAI
  ? 'https://picsum.photos/seed/deepseek/200'
  : route.query.avatar || 'https://picsum.photos/seed/user/200'
const placeholder = isAI ? '输入问题...' : '输入消息...'

// 监听登录状态
watch(() => userStore.isLoggedIn, (isLoggedIn) => {
  if (!isLoggedIn) {
    // 退出登录时跳转到登录页
    router.replace({
      path: '/login',
      query: { redirect: route.fullPath }
    })
  }
})

// 处理消息发送
const handleSend = async (message: string) => {
  if (isAI) {
    await handleAIMessage(message)
  } else {
    await handleNormalMessage(message)
  }
}

// 处理 AI 消息
const handleAIMessage = async (message: string) => {
  chatWindowRef.value.addMessage('user', message)

  try {
    chatWindowRef.value.setLoading(true)
    let currentMessage = ''

    const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/api/deepseek`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${userStore.token}`,
      },
      body: JSON.stringify({
        messages: chatWindowRef.value.messages.map(msg => ({
          role: msg.role === 'other' ? 'assistant' : msg.role,
          content: msg.content
        })),
      }),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body!.getReader()
    const decoder = new TextDecoder()

    // 添加 AI 回复占位
    chatWindowRef.value.addMessage('assistant', '')

    while (true) {
      const { value, done } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(5).trim()

          // 忽略连接成功消息
          if (data === '{"content": "连接成功"}') continue

          // 检查是否是结束标记
          if (data === '{"done":true}') continue

          try {
            const parsed = JSON.parse(data)
            if (parsed.error) {
              throw new Error(parsed.message)
            }

            if (parsed.content) {
              currentMessage += parsed.content
              const lastMessage = chatWindowRef.value.messages[chatWindowRef.value.messages.length - 1]
              if (lastMessage) {
                lastMessage.content = currentMessage
              }
            }
          } catch (e) {
            console.error('Error parsing chunk:', e)
          }
        }
      }
    }
  } catch (error: any) {
    showToast({
      message: error.message || '发送失败',
      type: 'fail',
    })
    // 移除失败的消息
    if (chatWindowRef.value.messages.length > 0) {
      chatWindowRef.value.messages.pop()
    }
  } finally {
    chatWindowRef.value.setLoading(false)
  }
}

// 处理普通消息
const handleNormalMessage = async (message: string) => {
  chatWindowRef.value.addMessage('user', message)

  try {
    chatWindowRef.value.setLoading(true)
    let currentMessage = ''

    const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/api/deepseek`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${userStore.token}`,
      },
      body: JSON.stringify({
        messages: [
          {
            role: 'system',
            content: '你现在是一个普通的聊天对象，请用简短、口语化的方式回复，不要太正式。不要使用 markdown 格式。'
          },
          ...chatWindowRef.value.messages.map(msg => ({
            role: msg.role === 'other' ? 'assistant' : msg.role,
            content: msg.content
          }))
        ],
      }),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body!.getReader()
    const decoder = new TextDecoder()

    // 添加回复占位
    chatWindowRef.value.addMessage('other', '')
    const messageIndex = chatWindowRef.value.messages.length - 1

    while (true) {
      const { value, done } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(5).trim()

          // 忽略连接成功消息
          if (data === '{"content": "连接成功"}') continue

          // 检查是否是结束标记
          if (data === '{"done":true}') continue

          try {
            const parsed = JSON.parse(data)
            if (parsed.error) {
              throw new Error(parsed.message)
            }

            if (parsed.content) {
              currentMessage += parsed.content
              chatWindowRef.value.messages[messageIndex].content = currentMessage
            }
          } catch (e) {
            console.error('Error parsing chunk:', e)
          }
        }
      }
    }
  } catch (error: any) {
    showToast({
      message: error.message || '发送失败',
      type: 'fail',
    })
    // 移除失败的消息
    chatWindowRef.value.messages.pop()
  } finally {
    chatWindowRef.value.setLoading(false)
  }
}

onMounted(() => {
  if (isAI) {
    chatWindowRef.value.addMessage('assistant', '你好！我是 DeepSeek AI 助手，很高兴为您服务。请问有什么我可以帮您的吗？')
  }
})
</script>

<style lang="less" scoped>
.chat-detail {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
</style>
